package com.ruoyi.reservationserver.controller;

import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.reservationserver.dao.ReservationsDao;
import com.ruoyi.system.domain.Court;
import com.ruoyi.system.domain.CourtStatistic;
import com.ruoyi.system.domain.StadiumStatistic;
import com.ruoyi.system.service.CourtStatisticService;
import com.ruoyi.reservationserver.service.ReservationsService;
import com.ruoyi.reservationserver.service.StadiumStatisticService;
import com.ruoyi.reservationserver.utils.Result;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Reservations;
import com.ruoyi.system.service.IReservationsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 预约管理Controller
 *
 * @author ruoyi
 * @date 2023-08-12
 */

public class ReservationsController extends BaseController
{
    @Autowired
    private IReservationsService reservationsService;
    @Resource
    private ReservationsService reservationsService1;
    @Resource
    private ReservationsDao reservationsDao;

    @Resource
    private CourtStatisticService courtStatisticService;

    @Resource
    private StadiumStatisticService stadiumStatisticService;

    /**
     * 查询预约管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:reservations:list')")
    @GetMapping("/list")
    public TableDataInfo list(Reservations reservations)
    {
        startPage();
        List<Reservations> list = reservationsService.selectReservationsList(reservations);
        return getDataTable(list);
    }

    /**
     * 导出预约管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:reservations:export')")
    @Log(title = "预约管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Reservations reservations)
    {
        List<Reservations> list = reservationsService.selectReservationsList(reservations);
        ExcelUtil<Reservations> util = new ExcelUtil<Reservations>(Reservations.class);
        util.exportExcel(response, list, "预约管理数据");
    }

    /**
     * 获取预约管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:reservations:query')")
    @GetMapping(value = "/{reservationId}")
    public AjaxResult getInfo(@PathVariable("reservationId") Long reservationId)
    {
        return success(reservationsService.selectReservationsByReservationId(reservationId));
    }

    /**
     * 新增预约管理
     */
    @PreAuthorize("@ss.hasPermi('system:reservations:add')")
    @Log(title = "预约管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Reservations reservations)
    {
        QueryWrapper<CourtStatistic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stadium_id", 1);

        CourtStatistic courtStatistic = courtStatisticService.getOne(queryWrapper);
        System.out.println("新增的预约数："+reservations.getReservationNum()+",/当前的预约数："+courtStatistic.getReservationNum());
        courtStatistic.setReservationNum((int) (courtStatistic.getReservationNum()+reservations.getReservationNum()));
        courtStatisticService.update(courtStatistic);

        QueryWrapper<StadiumStatistic> wrapper = new QueryWrapper<>();
        wrapper.eq("stadium_statistic_id", 1);
        StadiumStatistic stadiumStatistic = stadiumStatisticService.getOne(wrapper);
        stadiumStatistic.setTotalReservationNum(courtStatistic.getReservationNum());
        stadiumStatisticService.update(stadiumStatistic);
        return toAjax(reservationsService.insertReservations(reservations));

    }

    /**
     * 修改预约管理
     */
    @PreAuthorize("@ss.hasPermi('system:reservations:edit')")
    @Log(title = "预约管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Reservations reservations)
    {
        return toAjax(reservationsService.updateReservations(reservations));
    }

    /**
     * 删除预约管理
     */
    @PreAuthorize("@ss.hasPermi('system:reservations:remove')")
    @Log(title = "预约管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{reservationIds}")
    public AjaxResult remove(@PathVariable Long[] reservationIds)
    {
        for (int i = 0; i < reservationIds.length; i++) {
            Long id = reservationIds[i];
            Reservations reservations = reservationsService.selectReservationsByReservationId(id);
            QueryWrapper<CourtStatistic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("stadium_id", 1);
            CourtStatistic courtStatistic = courtStatisticService.getOne(queryWrapper);

            courtStatistic.setReservationNum((int) (courtStatistic.getReservationNum()-reservations.getReservationNum()));
            courtStatisticService.update(courtStatistic);

            QueryWrapper<StadiumStatistic> wrapper = new QueryWrapper<>();
            wrapper.eq("stadium_statistic_id", 1);
            StadiumStatistic stadiumStatistic = stadiumStatisticService.getOne(wrapper);
            stadiumStatistic.setTotalReservationNum((int) (stadiumStatistic.getTotalReservationNum()-reservations.getReservationNum()));
            stadiumStatisticService.update(stadiumStatistic);
        }
        return toAjax(reservationsService.deleteReservationsByReservationIds(reservationIds));
    }


    /**
     * 分页获取用户数据
     *
     * @param page
     * @param count
     * @return
     */
    @GetMapping
    public Result index(@RequestParam(value = "page", defaultValue = "1") int page,
                        @RequestParam(value = "count", defaultValue = "10") int count) {
        PageInfo<com.ruoyi.reservationserver.entity.Reservations> pageInfo = reservationsService1.selectReservationWithPage(page, count);
        return Result.success(pageInfo);
    }

    /**
     * 通过场地名查询预约记录
     *
     * @param courtName
     * @return
     */
    @GetMapping("selectReservationsByCourtName")
    public Result selectUserByAccount(@RequestParam String courtName) {
        List<com.ruoyi.reservationserver.entity.Reservations> reservationsList;
        if (courtName == null) {
            return Result.error("不能输入空信息");
        }
        reservationsList=reservationsDao.selectReservationsByCourtName(courtName);
        return Result.success(reservationsList);
    }


    /**
     * 编辑数据
     *
     * @param reservations 实体
     * @return 编辑结果
     */
    @PostMapping("/edit")
    public Result edit(@RequestBody com.ruoyi.reservationserver.entity.Reservations reservations) {
        try {
            if (reservations == null) {
                return Result.error("数据不能为空");
            }
            if (reservations.getReservationId() == null) {
                return Result.error("id不能为空");
            }
            this.reservationsService1.update(reservations);
            return Result.success();

        } catch (Exception e) {
            return Result.error("更新失败");
        }
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @GetMapping("/del")
    public Result deleteById(@RequestParam("reservationId") Integer id) {
        com.ruoyi.reservationserver.entity.Reservations reservations;
        try {
            reservations = reservationsService1.queryById(id);
            System.out.println(reservations);

            QueryWrapper<CourtStatistic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("stadium_id", 1);
            CourtStatistic courtStatistic = courtStatisticService.getOne(queryWrapper);
            if (this.reservationsService1.deleteById(id)) {
                courtStatistic.setReservationNum(courtStatistic.getReservationNum()-reservations.getReservationNum());
                courtStatisticService.update(courtStatistic);

                QueryWrapper<StadiumStatistic> wrapper = new QueryWrapper<>();
                wrapper.eq("stadium_statistic_id", 1);
                StadiumStatistic stadiumStatistic = stadiumStatisticService.getOne(wrapper);
                stadiumStatistic.setTotalReservationNum(stadiumStatistic.getTotalReservationNum()-reservations.getReservationNum());
                stadiumStatisticService.update(stadiumStatistic);

            } else {
                return Result.error("500", "出错啦");
            }


            return Result.success();
        } catch (Exception e) {
            System.out.println(e.toString());
            return Result.error("删除失败");
        }

    }
}
